<template>

  <Transition name="fade" mode="out-in">
    <div v-if="isLoading" key="loading" class="loading"></div>
    <div v-else
      class="view-scroll-wrapper hide-scroll h-full pt-[25vh] overflow-y-auto scroll-smooth mb:overflow-x-hidden"
      ref="scrollableComponent" @wheel="onWheel">
      <div ref="el" class="view-container min-w-[468px] etab-app-grid">
        <!-- <div class="widget" draggable="true"><div></div></div> -->
        <TransitionGroup name="group">
          <div viewType="itemContainer" :dragTester="item.type"
            class="px-[30px] py-[15px] icon-container z-[1] etab-app-item"
            :class="[!item?.size?.type ?setTypeClass(item.type):'']" :style="dynamicStyle(item)"
            v-for="(item, index) in list" :key="item.id" :data-dropid="item.id" @mousedown="onMouseDown($event, item)">
            <div class="w-full h-full d" @contextmenu.stop.prevent="showContextMenu(item, $event)">
              <ToDoCenter v-if="item.type?.includes(TYPE.WIDGET) && item.widgetType==='ToDoCenter'"
                :class="{ dragging: item.id === draggingId }"  :data="item" :data-dropid="item.id"
                :editing="contextMenuStore.menuActive === 'editHome'" @edit="showEditIcon" @remove="deleteWidget"
                @changePointerEvents="changePointerEvents">
              </ToDoCenter>
              <Icon v-if="item.type === TYPE.SITE" :class="{ dragging: item.id === draggingId }" :data-dropid="item.id"
                :data="item" :editing="contextMenuStore.menuActive === 'editHome'" @remove="deleteIcon"
                @edit="showEditIcon"></Icon>
              <Folder ref="folderIcon" v-if="item.type === TYPE.FOLDER" :class="{ dragging: item.id === draggingId }"
                :data="item" :data-dropid="item.id" @open="openFolder" @change-name="changeFolderName($event, item)">
              </Folder>
              <Test v-if="item.type === TYPE.COMPONENT" :class="{ dragging: item.id === draggingId }" :data="item"
                :data-dropid="item.id" :editing="contextMenuStore.menuActive === 'editHome'" @remove="deleteWidget">
              </Test>
            </div>
          </div>
        </TransitionGroup>
        <div class="view-add-btn px-[30px]">
          <div
            class="view-addbtn select-none flex-center cursor-pointer border-[1px] border-[rgba(255,255,255,0.6)] bg-[rgba(209,209,214,0.9)]"
            @click="addClick">
            <span class="text-white/60 text-[40px] font-thin">+</span>
          </div>
        </div>
      </div>
    </div>
  </Transition>
</template>
<script setup>
import { ref, computed, watchEffect, watch, nextTick, provide } from 'vue';
// import json from "./viewlist.json";
import { vOnClickOutside } from '@vueuse/components';
import { ElMessageBox } from 'element-plus';
import { useContextMenuStore, useIconListStore } from '../store';
import { TYPE } from '../api/types';
import IconApi from '../api/icon';
// import IconList from "./IconList.vue";
import Icon from '../elements/Icon.vue';
import Widget from '../elements/widget/Weather.vue';
import Folder from '../elements/Folder.vue';
import ToDoCenter from '@/components/toDoCenter/index.vue'
import Test from '../elements/test.vue'
import widgetApi from '@/api/widget.ts';
const emptyFolder = ref(null);

// 定义变量，判断点击和长按
const isClick = ref(null);
const draggingId = ref('');
const pointerEvents=ref('none')
const isDragging = ref(false);
provide('mousedown', onMouseDown);
provide('draggingId', draggingId);
provide('deleteFolderIcon', deleteFolderIcon);
provide('pointerEvents', pointerEvents)
provide('isDragging', isDragging)
const initFolder = {
  id: '',
  origin: 'add',
  type: 'folder',
  name: '文件夹',
  folderSize: 'mini',
};
const folderIcon = ref(null);
const getParentsAsStop = (el, stopSelector) => {
  let currentDom = el;
  const parents = [];
  while (currentDom !== window.document) {
    parents.unshift(currentDom);
    if (currentDom?.matches(stopSelector)) return parents;
    currentDom = currentDom.parentNode;
  }
  return parents;
};
let currentSelectfolder = null;
const draggingItem = ref(null);
const hoverItem = ref(null);
const hoverTimer = ref(null);

const mouseOffset = ref({ x: 0, y: 0 });
const changePointerEvents=val=>{
  pointerEvents.value=val
}

const hasSpecificParent = (element, parentSelector) =>{
  let current = element.parentNode;
  while (current) {
    if (current?.matches(parentSelector)) {
      return current;
    }
    current = current.parentNode;
  }
  return null;
}
function onMouseDown(e, item) {
  if (e.button !== 0) return; // 只响应左键点击
  // console.log(e.target, 'target');
  let { target } = e;
  if (!target.dataset.type) {
    const parentNode = hasSpecificParent(target, '.ticket-center');
    if (parentNode) {
      target = parentNode
    } else {
      return;
    }
  }
  
  
  sourceNodeInfo.target = target;
  sourceNodeInfo.type = target.dataset.type;

  // transition = getComputedStyle(target).transition;
  target.style.transition = 'none';

  const { left, top, width, height } = target.getBoundingClientRect();
  Object.assign(sourceNodeInfo, {
    width,
    height,
    left,
    dragId: target.dataset.dropid,
    top,
    offsetX: e.clientX - left,
    offsetY: e.clientY - top,
  });

  // 获取原始元素的实际尺寸
  cloneObj = target.cloneNode(true);
  cloneObj.classList.add('fixed-dom');
  Object.assign(cloneObj.style, {
    width: `${width}px`,
    height: `${height}px`,
    transform: `translate(${left}px ${top}px)`,
    opacity: 0,
  });
  document.body.appendChild(cloneObj);

  draggingItem.value = item;

  document.addEventListener('mousemove', onMouseMove);
  document.addEventListener('mouseup', onMouseUp);
}
let once = false;
const siteTester = (x, y, width, height) => {
  if (y > (height * 2) / 3) {
    return null;
  }
  if (x < width / 3  ) {
    return 'left';
  }
  if (x > (width * 2) / 3) {
    return 'right';
  }
  return 'center';
};
const folderAlertTester = (type) => {
  const lastfolderAlartState = window._lastfolderAlartState_;
  window._lastfolderAlartState_ = type;
  if (!lastfolderAlartState) {
    return null;
  }
  if (lastfolderAlartState !== window._lastfolderAlartState_) {
    window._lastfolderAction_ = setTimeout(() => {
      // 此处的延迟是为了给动作留出执行完成的时间，防止总是一个状态被误判为用户无意执行操作。
      delete window._lastfolderAction_;
      delete window._lastfolderAlartState_;
    }, 300 + 100);
    return window._lastfolderAlartState_;
  } else {
    if (window._lastfolderAction_) {
      return window._lastfolderAlartState_;
    }
  }
  return null;
};
const testerPointRule = {
  [TYPE.SITE]: siteTester,
  [TYPE.INNER_SITE]: (...arg) => {
    const testResult = siteTester(...arg);
    return `inner_${testResult}`;
  },
  [TYPE.WIDGET_A]: (x, y, width, height) => {
    if (y > (height * 2) / 3) {
      return null;
    }
    if (x < width / 6) {
      return 'left';
    }
    if (x > (width * 2) / 3) {
      return 'right';
    }
    return 'center';
  },
  [TYPE.COMPONENT]: (x, y, width, height) => {
    if (y > (height * 2) / 3) {
      return null;
    }
    if (x < width / 3) {
      return 'left';
    }
    if (x > (width * 2) / 3) {
      return 'right';
    }
    return 'center';
  },
  ['folder-alert']: (x, y, width, height) => {
    return folderAlertTester('inner');
  },
  ['folder-marker']: (x, y, width, height) => {
    return folderAlertTester('outer');
  },
  [TYPE.FOLDER]: (x, y, width, height) => {
    if (y > (height * 2) / 3) {
      return null;
    }
    if (x < width / 3) {
      return 'left';
    }
    if (x > (width * 2) / 3) {
      return 'right';
    }
    return 'center';
  },
};
let lastHoverFlag = null;
let moveTesterSleep = false;
const onMouseMove = (event) => {
  if (!draggingItem.value || !sourceNodeInfo.target) return;

  isDragging.value = true;

  if (cloneObj) {
    if (!once) {
      sourceNodeInfo.target.style.opacity = 0;
      cloneObj.style.opacity = 1;
      draggingId.value = draggingItem.value.id;
    }

    const top = event.clientY - sourceNodeInfo.offsetY;
    const left = event.clientX - sourceNodeInfo.offsetX;
    once = true;

    // 使用 requestAnimationFrame 来平滑更新位置
    requestAnimationFrame(() => {
      if (cloneObj){
        cloneObj.style.transform = `translate(${left}px, ${top}px)`;
      }
    });
  }

  // 处理 hover 时的元素交换
  const targetEl = getParentsAsStop(event.target, '[dragTester]')[0];
  if (targetEl === document) {
    clearTimeout(hoverTimer.value);
    return;
  }

  const hoverId = targetEl.dataset.dropid;
  if (hoverId === draggingItem.value.id) {
    clearTimeout(hoverTimer.value);
    return;
  }

  const dragTesterType = targetEl.getAttribute('dragTester');
  const { left, top, width, height } = targetEl.getBoundingClientRect();
  console.log(targetEl, targetEl.getBoundingClientRect(),"获取当前元素的大小")
  const offsetX = event.clientX - left;
  const offsetY = event.clientY - top;
  // debugger
  if (typeof testerPointRule[dragTesterType] !== 'function') {
    clearTimeout(hoverTimer.value);
    return;
  }
  console.log(offsetX, offsetY, width, height,"yuansu")
  const testResult = testerPointRule[dragTesterType](offsetX, offsetY, width, height);
  console.log(testResult,"获取到的拖拽信息")
  if (!testResult) {
    clearTimeout(hoverTimer.value);
    return;
  }

  const newHoverFlag = hoverId + '-' + testResult;
  if (newHoverFlag === lastHoverFlag) return;

  lastHoverFlag = newHoverFlag;
  clearTimeout(hoverTimer.value);

  hoverTimer.value = setTimeout(() => {
    switch (testResult) {
      case 'left':
        swapItems(draggingItem.value, hoverId, 'left');
        break;
      case 'right':
        swapItems(draggingItem.value, hoverId, 'right');
        break;
      case 'inner_left':
        swapfolderItems(draggingItem.value, hoverId, 'left');
        break;
      case 'inner_right':
        swapfolderItems(draggingItem.value, hoverId, 'right');
        break;
      case 'outer':
        removefolderItem(draggingItem.value, hoverId);
        break;
      case 'center':
        joinToFolder(draggingItem.value, hoverId);
        break;
    }
    lastHoverFlag = null;
    hoverTimer.value = null;
  }, 100);
};
const onMouseUp = (e) => {
  let target = sourceNodeInfo.target;
  target.style.opacity = 1;
  target.style.transition = transition;
  let isTrue = true;
  while (isTrue && target && target !== document.body) {
    if (target.classList.contains('dragging')) {
      isTrue = false;
    } else {
      target = target.parentNode;
    }
  }
  target.classList.remove('dragging');
  draggingId.value = '';
  sourceNodeInfo = {};
  once = false;
  removeCloneObj();
  isDragging.value = false;
  draggingItem.value = null;
  hoverItem.value = null;
  clearTimeout(hoverTimer.value);
  document.removeEventListener('mousemove', onMouseMove);
  document.removeEventListener('mouseup', onMouseUp);

  if (emptyFolder.value) {
    deleteIcon({ id: emptyFolder.value }, false)?.then(() => {
      // 保存数据
      updateData(list.value);
    });
    emptyFolder.value = null;
  } else {
    // 保存数据
    updateData(list.value);
  }
  updateToDoCenterPosition(draggingItem.value);
  // console.log(list);
};

const menuItems = ref([]);

const contextMenuStore = useContextMenuStore();

function showContextMenu(item, event) {
  const { type } = item;
  if (type === 'site') {
    menuItems.value = [
      { label: '编辑主页', value: 'editHome' },
      { label: '编辑图标', value: 'editIcon' },
      { label: '删除图标', value: 'deleteIcon' },
    ];
  } else if (type?.includes(TYPE.WIDGET)) {
    menuItems.value = [
      { label: '编辑组件', value: 'editWidget' },
      { label: '删除组件', value: 'deleteWidget' },
    ];
  }else if(type===TYPE.COMPONENT){
    menuItems.value = [
      { label: '大', value: 'changeBig' },
      { label: '中', value: 'changeMiddle' },
      { label: '小', value: 'changeSmall' },
      { label: '编辑组件', value: 'editWidget' },
      { label: '删除组件', value: 'deleteWidget' },
    ];
  } else {
    menuItems.value = [
      { label: '释放', value: 'releaseFolder' },
      { label: '删除文件夹', value: 'deleteFolder' },
    ];
  }
  contextMenuStore.setTarget(item);
  contextMenuStore.setContextMenu(menuItems.value);
  contextMenuStore.setPosition(event);
}

watchEffect(() => {
  switch (contextMenuStore.menuActive) {
    case 'deleteIcon':
      deleteIcon(contextMenuStore.target);
      contextMenuStore.setMenuActive('');
      break;
    case 'deleteWidget':
      deleteWidget(contextMenuStore.target);
      contextMenuStore.setMenuActive('');
      break;

    case 'deleteFolder':
      ElMessageBox.confirm('删除文件夹将同时删除文件夹下的所有图标。', '提醒', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          deleteFolder(contextMenuStore.target.id);
          contextMenuStore.setMenuActive('');
        })
        .catch(() => {
          contextMenuStore.setMenuActive('');
        });
      break;
    case 'releaseFolder':
      releaseFolder(contextMenuStore.target.id);
      contextMenuStore.setMenuActive('');
      break;
    case 'deleteFolderIcon':
      deleteFolderIcon(contextMenuStore.target);
      contextMenuStore.setMenuActive('');
      break;
    case 'changeBig':
      changeSize(contextMenuStore.target,'big')
      contextMenuStore.setMenuActive('');
      break;
    case 'changeMiddle':
      changeSize(contextMenuStore.target, 'middle')
      contextMenuStore.setMenuActive('');
      break
    case 'changeSmall':
      changeSize(contextMenuStore.target, 'small')
      contextMenuStore.setMenuActive('');
      break
    default:
      break;
  }
});
function changeSize(target,type){
  // 要切换的大小
  const changeSize = target?.styleList?.filter(item=>{
    return item.type==type
  })
  list.value=list.value?.map(item=>{
    return {
      ...item,
      size: target.id==item.id?changeSize?.[0]:item.size
    }
  })
  updateData(list.value)
}
function deleteFolder(id) {
  deleteIcon({ id });
}

function getFolderIndex(target) {
  let childIndex = -1;
  const parentIndex = list.value.findIndex((item) => {
    if (item.children) {
      childIndex = item.children.findIndex((child) => child.id === target.id);
      if (childIndex > -1) {
        return true;
      }
    }
    return false;
  });
  return { parentIndex, childIndex };
}

function deleteFolderIcon(target) {
  const { parentIndex, childIndex } = getFolderIndex(target);
  if (parentIndex > -1) {
    const parent = list.value[parentIndex];
    parent.children.splice(childIndex, 1);
    if (parent.children.length === 1) {
      list.value.splice(parentIndex, 1, parent.children[0]);
      // 需要调删除接口删除文件夹
      deleteIcon({ id: parent.id }, false).then(() => {
        // 保存数据
        updateData(list.value);
      });
    } else {
      updateData(list.value);
    }
  }
}

function editFolderIcon(item) {
  const { parentIndex, childIndex } = getFolderIndex(item);
  if (parentIndex > -1) {
    const parent = list.value[parentIndex];
    parent.children.splice(childIndex, 1, item);
    updateData(list.value);
  }
}

function releaseFolder(id) {
  const clone = [...list.value];
  const index = clone.findIndex((item) => item.id === id);
  if (index > -1) {
    // const [folder] = clone.splice(index, 1);
    const [first, ...rest] = clone[index].children;
    clone.splice(index, 1, first);
    clone.push(...rest);
    deleteIcon({ id }, false).then(() => {
      // 保存数据
      updateData(clone);
    });
  }
}

const iconListStore = useIconListStore();

const props = defineProps(['currentCate', 'currentPage', 'addHomepageItem']);
const emits = defineEmits(['showItems','changeActiveIndex']);

const isLoading = ref(false);
const list = ref([]);
// const demo = new Array(60).fill(json[0]);
// list.value = demo;
// list.value = json;
function changeFolderName(name, item) {
  item.name = name;
  updateData(list.value);
}

const getIconList = (useLoading = false) => {
  if (useLoading) {
    isLoading.value = true;
  }
  IconApi.get({ id: props.currentCate }).then((res) => {
    isLoading.value = false;
  });
};
const getIconDetail = (useLoading = false) => {
  if (useLoading) {
    isLoading.value = true;
  }
  IconApi.getDetail({ id: props.currentCate }).then((res) => {
    // list.value = res.sort((a, b) => a.orderSort - b.orderSort);
    // console.log(res, '------')
    list.value = JSON.parse(res.dataJson);
    isLoading.value = false;
  });
};
const translateY = ref('');
watch(
  () => props.currentPage,
  (newVal, oldVal) => {
    if (newVal > oldVal) {
      translateY.value = 'translateY(200px)';
    } else {
      translateY.value = 'translateY(-200px)';
    }
  }
);
watch(
  () => props.addHomepageItem,
  (val) => {
    if (val) {
      if (!list.value) {
        list.value = []
      }

      // list.value.push({
      //   ...val, type: 'sysWidget'})
      addIcon({ ...val.item, parentId: val.parentId })
    }
  }, {
  deep: true
}
);

watchEffect(() => {
  if (props.currentCate) {
    getIconDetail(true);
  }
});
getIconList(true);
const iconWebVisible = ref(false);

const closeModal = () => {
  iconWebVisible.value = false;
};

const addClick = () => {
  iconWebVisible.value = true;
  emits('showItems');
};

const deleteIcon = (item, refresh) => {
  const copy = list?.value?.filter(ele => {
    return ele.id != item.id
  });
  updateData(copy);
  // return new Promise((resolve) => {
  //   IconApi.delete([{ id: item.id }]).then((res) => {
  //     if (refresh !== false) {
  //       getIconDetail();
  //     }
  //     resolve();
  //   });
  // });
};
const deleteWidget = (item, refresh) => {
  const copy = list?.value?.filter(ele => {
    return ele.id != item.id
  });
  updateData(copy);
  // return new Promise((resolve) => {
  //   IconApi.delete([{ id: item.id }]).then((res) => {
  //     if (refresh !== false) {
  //       getIconDetail();
  //     }
  //     resolve();
  //   });
  // });
};

const showEditIcon = (item) => {
  // todo
  // console.log("iii", item);
  // 跳转编辑页
};

function updateData(data, parentId) {
  let params = {
    "id": parentId ||props.currentCate,
    "dataJson": JSON.stringify(data),
  }
  data = JSON.parse(JSON.stringify(data));
  // console.log(data,'3 ew3333333 ')
  data.forEach((item) => {
    item.id = props.currentCate;
    if (item.id && item.id.length < 15) {
      delete item.id;
    }
  });
  // if (refresh) {
    return IconApi.edit(params).then(() => {
      // getIconList();
      getIconDetail();
      if (parentId) emits('changeActiveIndex', parentId)
    });
  // }
  return IconApi.edit(data);
}

const addIcon = (item) => {
  const copy = [...list?.value, item];
  updateData(copy,item.parentId);
};

const editIcon = (item) => {
  const copy = [...list.value];
  const index = copy.findIndex((i) => i.id === item.sysIconId);
  if (index > -1) {
    copy.splice(index, 1, item);
    updateData(copy);
  } else {
    editFolderIcon(item);
  }
};

defineExpose({
  addIcon,
  editIcon,
});

watchEffect(() => {
  if (contextMenuStore.menuActive === 'addIcon') {
    addClick();
  }
});
const scrollableComponent = ref(null);
function onWheel(event) {
  if (scrollableComponent.value) {
    const { scrollTop, scrollHeight, clientHeight } = scrollableComponent.value;

    const canScroll = scrollHeight > clientHeight;

    if (canScroll) {
      const isAtTop = scrollTop === 0;
      const isAtBottom = scrollTop + clientHeight + 2 >= scrollHeight;
      const isScrollingUp = event.deltaY < 0;
      const isScrollingDown = event.deltaY > 0;

      if ((isAtTop && isScrollingUp) || (isAtBottom && isScrollingDown)) {
        // 如果在顶部且向上滚动，或在底部且向下滚动，则允许事件冒泡
        return;
      }

      // 否则阻止事件冒泡
      event.stopPropagation();
    }
  }
}
const containerStyle = (item) => {
  return computed(() => {
    if (item.type === 'widget') {
      return {
        'grid-column': 'span 2',
        'grid-row': item.widgetSize == 'm' ? 'span 2' : 'span 1',
      };
    }
    return {};
  });
};

let cloneObj = null;
let transition = '';
let sourceNodeInfo = {};

const swapItems = (dragged, hoverId, splicePosition) => {
  const draggedIndex = list.value.findIndex((item) => item.id === dragged.id);
  const [movedItem] = list.value.splice(draggedIndex, 1);
  let spliceIndex = list.value.findIndex((item) => item.id === hoverId);
  if (splicePosition === 'right') {
    spliceIndex += 1;
  }
  list.value.splice(spliceIndex, 0, movedItem);
};

const swapfolderItems = (...arg) => {
  currentSelectfolder.swapItems(...arg);
};

const removefolderItem = (dragged, hoverId) => {
  if (!currentSelectfolder) {
    throw new Error('移出文件夹出错啦');
  }
  const folderIndex = list.value.findIndex((item) => item.id === hoverId);
  const folder = list.value[folderIndex];
  const removeItemIndex = folder.children.findIndex(
    (item) => item.id === dragged.id
  );
  const removeItem = folder.children[removeItemIndex];
  folder.children.splice(removeItemIndex, 1);
  if (folder.children.length === 1) {
    list.value.splice(folderIndex, 1, folder.children[0]);
    // 需要调删除接口删除文件夹
    emptyFolder.value = folder.id;
  }
  list.value.push(removeItem);
  currentSelectfolder.closeFolder();
};

const joinToFolder = (dragged, hoverId) => {
  const draggedItemIndex = list.value.findIndex(
    (item) => item.id === dragged.id
  );
  const joinTargetIndex = list.value.findIndex((item) => item.id === hoverId);
  const joinTarget = list.value[joinTargetIndex];
  const draggedItem = dragged;
  if (!joinTarget || !draggedItem) {
    throw new Error('合并入文件夹出错啦');
  }
  if (draggedItem.type !== TYPE.SITE) {
    return;
  }
  if (joinTarget.type === TYPE.FOLDER) {
    list.value.splice(draggedItemIndex, 1);
    // 在被抓住的数据上 增加一个当前是否处于抓取中的flag，有这个flag的css设置为透明隐藏
    joinTarget.children.push(draggedItem);
    currentSelectfolder = folderIcon.value.find(
      (folder) => folder.id === joinTarget.id
    );
    currentSelectfolder.openFolder();
  } else {
    if (joinTarget.type === TYPE.SITE) {
      moveTesterSleep = true;
      const newFolder = createFolder(dragged, joinTarget);
      nextTick(() => {
        currentSelectfolder = folderIcon.value.find(
          (folder) => folder.id === newFolder.id
        );
        currentSelectfolder.openFolder();
        moveTesterSleep = false;
      });
    }
  }
};
const createFolder = (dragged, over) => {
  const id = Math.random().toString(36).slice(2);
  const folder = {
    ...initFolder,
    id,
    children: [over, dragged],
  };
  // 在被抓住的数据上 增加一个当前是否处于抓取中的flag，有这个flag的css设置为透明隐藏
  const draggedIndex = list.value.findIndex((item) => item.id === dragged.id);
  const overIndex = list.value.findIndex((item) => item.id === over.id);
  const copy = combineItems([...list.value], draggedIndex, overIndex, folder);
  list.value = copy;
  return folder;
};

function combineItems(arr, index1, index2, combined) {
  // 确保索引1小于索引2
  if (index1 > index2) {
    [index1, index2] = [index2, index1];
  }

  // 保存需要合并的两项
  // let combined = combined;

  // 移除两个索引处的项，从后往前移除以避免索引变化
  arr.splice(index2, 1); // 先移除index2处的项
  arr.splice(index1, 1); // 再移除index1处的项

  // 在index1处插入新数组
  arr.splice(index1, 0, combined);

  return arr;
}

function removeCloneObj() {
  if (cloneObj) {
    cloneObj?.remove();
    cloneObj = null;
  }
}

function openFolder(id) {
  currentSelectfolder = folderIcon.value.find((folder) => folder.id === id);
}
//更新位置
const updateToDoCenterPosition = (item) => {
  if (item && item.type === TYPE.TABLE) {
    // 更新 ToDoCenter 位置
    const el = document.querySelector(`[data-dropid="${item.id}"]`);
    if (el) {
      // 可能需要根据拖拽的实际情况进行位移处理
      el.style.transform = `translate(${item.newPositionX}px, ${item.newPositionY}px)`;
    }
  }
};
// 设置样式
const setTypeClass = type => {
  if (type?.includes(TYPE.WIDGET)){
    // return 'app-size-grid-max app-size-max';
  } else if (type === TYPE.SITE){
    return "app-size-grid-min app-size-min"
  
  } else if (type === TYPE.COMPONET) {
    if (size?.type==='big')
    return "`app-size-grid-min app-size-min`"
  }else{
    return "app-size-grid-min app-size-min"
  }
}
const dynamicStyle=item=>{
  if (item?.size?.size){
    const size = item?.size?.size?.split('*')||[6,4]
    return {
      gridRow: `span ${size[1]}`,
      gridColumn: `span ${size[0]}`,
      width: `calc(72px * ${size[0]} + 40px * ${size[0]})`,
      height:  `calc(72px * ${size[1]} + 40px * ${size[1]})`
    }
  }
}
</script>
<style scoped lang="scss">
.view-scroll-wrapper {
  transition: transform 0.3s;

  &::-webkit-scrollbar {
    display: none;
    /* Chrome, Safari, and Opera */
  }
}

.view-container {
  // grid-template-columns: repeat(auto-fill, 132px);
  // width: min(1392px, -200px + 100vw);
  // justify-content: center;
  padding-left: min(180px, -234px + 50vw);
  padding-right: min(180px, -234px + 50vw);
}

// 轻微抖动动画
@keyframes shake {
  0% {
    transform: rotate(-2deg);
  }

  50% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(2deg);
  }
}

.view-addbtn {
  filter: drop-shadow(rgba(0, 0, 0, 0.05) 0 4px 12px);
  font-size: 38px;
  line-height: 72px;
  transition: all 0.2s;
  width: 72px;
  border-radius: var(--icon-rounded, 20px);
}

:deep(.dragging) {
  opacity: 0 !important;
  cursor: pointer;
  z-index: 0;
}

.group-move {
  transition: transform 0.3s ease;
}

.fade-enter-active,
.fade-leave-active {
  transition: transform 0.15s ease;
}

.icon-container {
  position: relative;
}

.drag-tester {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 10;
  display: grid;
  grid-auto-flow: column;
  grid-template-columns: repeat(30%);
  opacity: 0.3;

  &-left {
    background-color: red;
  }

  &-right {
    background-color: blue;
  }

  &-center {
    background-color: green;
  }
}

.fade-enter-from {
  // opacity: 0;
  transform: v-bind(translateY);
}

.etab-app-grid {
  position: relative;
  box-sizing: border-box;
  display: grid;
  grid-template-columns: repeat(auto-fill, calc(var(--icon-size) + var(--icon-gap-y)));
  grid-auto-flow: dense;
  justify-content: center;
  // max-width: 1650px;
  padding-top: 2vh;
  color: #fff;
  -webkit-user-select: none;
  -moz-user-select: none;
  user-select: none;

  .etab-app-item {
    position: relative;
    box-sizing: border-box;
    display: inline-block;
    justify-content: center;
    padding: 0 calc(var(--icon-gap-y) / 2 - 0px) calc(var(--icon-gap-x)) calc(var(--icon-gap-y) / 2 - 0px);
    -webkit-user-select: none;
    -moz-user-select: none;
    user-select: none;
    border-radius: var(--icon-radius);
    opacity: var(--icon-opacity);
    cursor: pointer;
  }

  .app-size-grid-max {
    grid-row: span 4;
    grid-column: span 6;
  }

  .app-size-max {
    width: calc(var(--icon-size)* 6 + var(--icon-gap-y)* 6);
    height: calc(var(--icon-size)* 4 + var(--icon-gap-x)* 4);
  }

  .app-size-grid-min,
  .app-size-grid-1x1 {
    grid-row: span 1;
    grid-column: span 1;
  }

  .app-size-min {
    width: calc(var(--icon-size) + var(--icon-gap-y));
    height: calc(var(--icon-size) + var(--icon-gap-x));
    text-align: center;
  }

  .app-size-grid-2x2 {
    grid-row: span 2;
    grid-column: span 2;
  }

  .app-size-2x2 {
    width: calc(var(--icon-size)* 2 + var(--icon-gap-y)* 2);
    height: calc(var(--icon-size)* 2 + var(--icon-gap-x)* 2);
  }
}

.fixed-dom {
  transition: transform 0.2s ease;
}
</style>
